<template>
  <div class="wrapper">
    <template v-if="props.showType=='bg'">
      <div v-for="(n, index) in state.displayValue" :key="index" class="number-char">
        <span class="num-box-item"  :class="n==',' || n=='，'? 'no-bg' : 'lll'">{{ n }}</span>
      </div>
    </template>
    <template v-else-if="props.showType=='tms-bg'">
      <div class="glowing-wrapper">
           <!-- 根据UI效果隐藏小提示框 -->
        <!-- <div class="add-tips" v-if="lastNumNew">+{{lastNumNew}}</div> -->
        <span v-for="(n, index) in state.displayValue" :key="index">
          <span class="glowing-numbers" :data-content="n">{{ n }}</span>
        </span>
      </div>
    </template>
    <template v-else>
      <div>
        <span v-for="(n, index) in state.displayValue" :key="index">
          {{ n }}
        </span>
      </div>
    </template>
  </div>
</template>

<script setup>
  /* eslint-disable */
// eslint-disable-next-line vue/no-setup-props-destructure
import { ref, onMounted, onUnmounted, reactive } from "@vue/runtime-core";
import { watch, computed, defineProps ,defineEmits} from 'vue';
import { requestAnimationFrame, cancelAnimationFrame } from './requestAnimationFrame.js'
// 定义父组件传递的参数
const props = defineProps({
  tipData:{
    type: Number,
  },
  showType:{
    type: String,
    required: false,
    default: 'bg'
  },
  start: {
    type: Number,
    required: false,
    default: 0
  },
  end: {
    type: Number,
    required: false,
    default: 0
  },
  duration: {
    type: Number,
    required: false,
    default: 5000
  },
  autoPlay: {
    type: Boolean,
    required: false,
    default: true
  },
  decimals: {
    type: Number,
    required: false,
    default: 0,
    validator (value) {
      return value >= 0
    }
  },
  decimal: {
    type: String,
    required: false,
    default: '.'
  },
  separator: {
    type: String,
    required: false,
    default: ','
  },
  prefix: {
    type: String,
    required: false,
    default: ''
  },
  suffix: {
    type: String,
    required: false,
    default: ''
  },
  useEasing: {
    type: Boolean,
    required: false,
    default: true
  },
  easingFn: {
    type: Function,
    default(t, b, c, d) {
      return c * (-Math.pow(2, -10 * t / d) + 1) * 1024 / 1023 + b;
    }
  }
})
const lastNumNew = ref(0)
watch(() => props.tipData, () => {
  if (props.tipData) {
    // console.log('tipData', props.tipData);
    lastNumNew.value = Number(props.tipData).toLocaleString()
    // console.log('lastNumNew', lastNumNew.value);
  }
})

const isNumber = (val) => {
  return !isNaN(parseFloat(val))
}

// 格式化数据，返回想要展示的数据格式
const formatNumber = (val) => {
  if(!val) return
  val = (typeof val=='number')?val.toFixed(props.default):val
  val += ''
  const x = val.split('.')
  let x1 = x[0]
  const x2 = x.length > 1 ? props.decimal + x[1] : ''
  const rgx = /(\d+)(\d{3})/
  if (props.separator && !isNumber(props.separator)) {
    while (rgx.test(x1)) {
      x1 = x1.replace(rgx, '$1' + props.separator + '$2')
    }
  }
  return props.prefix + x1 + x2 + props.suffix
}

// 相当于vue2中的data中所定义的变量部分
const state = reactive({
  localStart: props.start,
  displayValue: formatNumber(props.start),
  printVal: null,
  paused: false,
  localDuration: props.duration,
  startTime: null,
  timestamp: null,
  remaining: null,
  rAF: null
})

// 定义一个计算属性，当开始数字大于结束数字时返回true
const stopCount = computed(() => {
  return props.start > props.end
})
// 定义父组件的自定义事件，子组件以触发父组件的自定义事件
const emits = defineEmits(['onMountedcallback', 'callback'])

const startCount = () => {
  state.localStart = props.start
  state.startTime = null
  state.localDuration = props.duration
  state.paused = false
  state.rAF = requestAnimationFrame(count)
}

watch(() => props.start, () => {
  if (props.autoPlay) {
    startCount()
  }
})

watch(() => props.end, () => {
  if (props.autoPlay) {
    startCount()
  }
})
// dom挂在完成后执行一些操作
onMounted(() => {
  if (props.autoPlay) {
    startCount()
  }
  emits('onMountedcallback')
})
// 暂停计数
// const pause = () => {
//   cancelAnimationFrame(state.rAF)
// }
// 恢复计数
// const resume = () => {
//   state.startTime = null
//   state.localDuration = +state.remaining
//   state.localStart = +state.printVal
//   requestAnimationFrame(count)
// }

// const pauseResume = () => {
//   if (state.paused) {
//     resume()
//     state.paused = false
//   } else {
//     pause()
//     state.paused = true
//   }
// }

// const reset = () => {
//   state.startTime = null
//   cancelAnimationFrame(state.rAF)
//   state.displayValue = formatNumber(props.start)
// }

const count = (timestamp) => {
  if (!state.startTime) state.startTime = timestamp
  state.timestamp = timestamp
  const progress = timestamp - state.startTime
  state.remaining = state.localDuration - progress
  // 是否使用速度变化曲线
  if (props.useEasing) {
    if (stopCount.value) {
      state.printVal = state.localStart - props.easingFn(progress, 0, state.localStart - props.end, state.localDuration)
    } else {
      state.printVal = props.easingFn(progress, state.localStart, props.end - state.localStart, state.localDuration)
    }
  } else {
    if (stopCount.value) {
      state.printVal = state.localStart - ((state.localStart - props.end) * (progress / state.localDuration))
    } else {
      state.printVal = state.localStart + (props.end - state.localStart) * (progress / state.localDuration)
    }
  }
  if (stopCount.value) {
    state.printVal = state.printVal < props.end ? props.end : state.printVal
  } else {
    state.printVal = state.printVal > props.end ? props.end : state.printVal
  }

  state.displayValue = formatNumber(state.printVal)
  if (progress < state.localDuration) {
    state.rAF = requestAnimationFrame(count)
  } else {
    emits('callback')
  }
}
// 组件销毁时取消动画
onUnmounted(() => {
  cancelAnimationFrame(state.rAF)
})
</script>
<style lang="scss" scoped>
.num-box-item{
  background: #ccc;
  margin-right:10px;
  width: 40px;
  height: 60px;
  text-align: center;
  background: url('/src/assets/number_bg.png') no-repeat 0 0;
  background-size: 100% 100%;
  font-weight: bold;
}
  .no-bg{
    background: none !important;
    width: 20px !important;
  }
  .wrapper{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .glowing-wrapper{
    position: relative;
    padding-top: 30px;
    span{
      display: inline-block;
      padding: 0px 1px;
   }   
  }
.glowing-numbers{
  font-weight: bold;
  font-size: 75px;
  background-image: linear-gradient(to bottom, #E9F2FF, #0367F1);    
  background-clip:text;    
  -webkit-text-fill-color:transparent;
   text-shadow: -10 -10 10px #4091FF, /* 外发光 */ 
}
.add-tips{
    width: 60px;
    height: 23px;
    line-height: 23px;
    position: absolute;
    right: 5px;
    top: -10px;
    background: #ccc;
    font-size: 12px;
    color: #030C28;
    letter-spacing: 0;
    text-align: center;
    font-weight: 500;
    background-image: linear-gradient(0deg, #4091FF 19%, #4091FF 28%, #B6F0FF 100%);
    border-radius: 5px;
    margin: 1em auto;
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.19), 0 6px 6px rgba(0, 0, 0, 0.23);
    &::before {
        content: '';
        position: absolute;
        bottom: 0;
        right: 20px;
        width: 0;
        height: 0;
        border: 10px solid transparent;
        border-top-color: #4091FF;
        border-bottom: 0;
        border-left: 0;
        margin-left: 10px;
        margin-bottom: -8px;
      }
      }
</style>